import React, { useState, useRef } from 'react';
import { Menu } from 'antd';
import { useClickAway } from 'ahooks';
import Tree from '@/zero/components/Tree';
import styles from './index.less';

const renderMenuItems = items =>
  items.map((item, index) => {
    const { children, ...rest } = item;
    if (children) {
      return (
        <Menu.SubMenu {...rest} key={index}>
          {renderMenuItems(children)}
        </Menu.SubMenu>
      );
    }
    return item.type === 'divider' ? (
      <Menu.Divider key={index} />
    ) : (
      <Menu.Item key={index} disabled={item.disabled}>
        {item.title}
      </Menu.Item>
    );
  });

/**
 * 简易 Tree => 右键菜单
 */
const Index = props => {
  const {
    menuItems,
    onRightClick,

    value,
    onChange,

    // eslint-disable-next-line
    beforeShow = (resolve, reject) => {
      resolve();
    },
    ...rest
  } = props;

  const [menuVisible, setMenuVisible] = useState(false);

  const [selectedNode, setSelectedNode] = useState({
    x: 0,
    y: 0,
  });

  const ref = useRef();

  useClickAway(() => {
    setMenuVisible(false);
  }, ref);

  return (
    <>
      <Tree
        {...rest}
        checkable={false}
        multiple={false}
        value={[].concat(value)}
        onChange={keys => {
          if (keys[0]) {
            onChange(keys[0]);
          }
        }}
        onRightClick={({ event, node }) => {
          if (menuItems) {
            const nodeProps = node.props;
            if (`${nodeProps.value}` === `${value}`) {
              const { clientX, clientY } = event;

              new Promise((resolve, reject) => {
                beforeShow(resolve, reject, { nodeProps, currentValue: value });
              }).then(() => {
                setSelectedNode({
                  ...nodeProps,
                  x: clientX - 1,
                  y: clientY - 1,
                });
                setMenuVisible(true);
              });
            }
          }
          if (onRightClick) {
            onRightClick({ event, node });
          }
        }}
      />

      {menuItems && (
        <div style={menuVisible ? { display: 'block' } : { display: 'none' }} ref={ref}>
          <Menu
            selectable={false}
            style={{
              position: 'fixed',
              left: selectedNode.x,
              top: selectedNode.y,
            }}
            className={styles.menu}
            onClick={() => {
              setMenuVisible(false);
            }}
          >
            {renderMenuItems(typeof menuItems === 'function' ? menuItems(selectedNode) : menuItems)}
          </Menu>
        </div>
      )}
    </>
  );
};

Index.displayName = 'SimpleTree';
export default Index;
